#!/bin/bash

set -e

if [[ -n "${RF_DEBUG}" ]]; then
    set -x
fi

# fail without RF_SETTINGS_BUCKET
set -u

DIR="$(dirname "${0}")/../"

function usage() {
    echo -n \
"Usage: $(basename "$0")

Bootstrap development environment.

--containers builds containers / pulls postgres and memcached
--env        pulls .env file from S3
--sbtopts    pulls .sbtopts from S3
"
}

function build_containers() {
    echo "Building containers / pulling postgres and memcached"

    ensure_dirs

    pushd "${DIR}"

    docker-compose \
        -f "${DIR}/docker-compose.yml" \
        build
    docker-compose \
        -f "${DIR}/docker-compose.yml" \
        pull postgres memcached

    popd
}

function pull_env() {
    echo "Pulling .env from s3://${RF_SETTINGS_BUCKET}"
    pushd "${DIR}"

    aws s3 cp "s3://${RF_SETTINGS_BUCKET}/.env" ".env"

    popd
}

function override_build_repos() {
    echo "Overriding repository configuration for ${1}"
    echo "-Dsbt.override.build.repos=true" >> .sbtopts
    echo "-Dsbt.repository.config=project/${1}/repositories" >> .sbtopts
}

function ensure_dirs() {
    # Ensure that a directory exists to house AWS profiles.
    mkdir -p "${HOME}/.aws"
}

function generate_sbtopts() {
    echo "Generating .sbtopts"
    pushd "${DIR}"

    cp .sbtopts.sample .sbtopts

    if host nexus.rasterfoundry.internal; then
        override_build_repos "ci"
    fi

    sort .sbtopts | uniq > cleaned_sbtopts
    mv cleaned_sbtopts app-backend/.sbtopts

    popd
}

if [ "${BASH_SOURCE[0]}" = "${0}" ]; then
    if [ "${1:-}" = "--help" ]; then
        usage
    elif [ "${1:-}" = "--containers" ]; then
        build_containers
    elif [ "${1:-}" = "--env" ]; then
        pull_env
    elif [ "${1:-}" = "--sbtopts" ]; then
        generate_sbtopts
    else
        pull_env
        generate_sbtopts
        build_containers
    fi
fi
